#include<vector>
#include<iostream>
#include<pthread.h>
#include<unistd.h>
#include<string>
#include<cstdlib>
using namespace std;
//发放200张票
int tickets=200; 
 pthread_mutex_t lock;
  pthread_cond_t _con;
//用一个类来存储线程数据
class ThreadData
{
  public:
      ThreadData(int num,pthread_mutex_t *mtx )
      {
            ThreadName="thread--"+to_string(num);
              _mutex=mtx;
      }
  
    string ThreadName;
    pthread_mutex_t* _mutex;
    
};

void* ticket(void*args)
{
  //模拟抢票
    ThreadData*td = static_cast<ThreadData*>(args);
   const char* name=td->ThreadName.c_str();
   while(true)
  {
    pthread_mutex_lock(td->_mutex);
    pthread_cond_wait(&_con,td->_mutex);
     if(tickets>0)
    {
     
      printf("who=%s,票的数量为：%d\n",name,tickets);
      --tickets;
      
   

    }
    else
    { 
      
    break;}
    
    pthread_mutex_unlock(td->_mutex);
    //usleep(10000);
   }
   
    printf("quit......\n");
    return nullptr;
}
int main()
{
   pthread_mutex_init(&lock,nullptr);
   pthread_cond_init(&_con,nullptr);
 
  vector<pthread_t>tids;//用容器存放每一个线程tid
  vector<ThreadData*>data;//容器存放的是每一个结构体指针
  
  for(int i=1;i<5;i++)
  {

    pthread_t tid;
    ThreadData*_data=new ThreadData(i,&lock);
    data.push_back(_data);
  //创建四个线程,并调用函数来完成任务
    pthread_create(&tid,nullptr,ticket,data[i-1]);
    tids.push_back(tid);
  }

  while(1)
  {
      usleep(1000);
    
      pthread_cond_signal(&_con);//通过信号在终止程序.
      
  }
      
  //这时主线程来进行对其他线程的回收，防止内存泄漏
  for(auto x:tids)
  {
    pthread_join(x,nullptr);
  }
  //释放容器里的类
  for(auto td:data)
  {
    delete td;
  }
  pthread_mutex_destroy(&lock);
  pthread_cond_destroy(&_con);
  return 0;
}
